using System;
using System.Threading.Tasks;
using Gj.Galaxy.Logic;
using Unity.Services.Core;
using UnityEngine;

namespace Gj.UnityCloud
{
    public class UnityCloud
    {

        public static UnityCloud Instance;
        public static UnityCloudSettings settings;

        static UnityCloud()
        {
            settings = LoadSettings();
            Instance = new UnityCloud();

        }

        private static UnityCloudSettings LoadSettings()
        {
            var loadedSettings = (UnityCloudSettings)Resources.Load("UnityCloudSettings", typeof(UnityCloudSettings));
            if (loadedSettings == null)
            {
                loadedSettings = ScriptableObject.CreateInstance<UnityCloudSettings>();
                Debug.LogError("UnityCloudSettings is not exist (Resources)");
            }

            return loadedSettings;
        }

        public static async Task Init()
        {
            try
            {
                var options = new InitializationOptions();

                await UnityServices.InitializeAsync(options);
            }
            catch (Exception exception) {
                // An error occurred during initialization.
            }

        }

        public static async Task Login(GamePlayer player)
        {
            try
            {
                await Auth.Login(player);
            }
            catch (Exception e)
            {
                Debug.LogError(e);
                try
                {
                    await Auth.Login(player);
                }
                catch (Exception ee)
                {
                    throw ee;
                }
            }
        }
    }
}